package com.d404.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LoggingMXBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;
import com.d404.server.Login2.LoginBack.Classify;

import helpers.BeanHelper;
import im.beans.AddNewFriends;
import im.beans.Classify_User;
import im.beans.User;
import manager.DefaultSessionManager;
import manager.PersistentManager;

/**
 * Servlet implementation class Login
 */
public class Login2 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login2() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		// 返回信息
		LoginBack lb = new LoginBack();

		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String deviceId = request.getParameter("UUID");

		// 進行檢查
		if (userName == null || password == null || deviceId == null) {
			lb.setStatus(LoginBack.FALSE);
			response.getWriter().append(JSON.toJSONString(lb));
			return;
		}

		String userID = "";// 用户ID
		String status = "9";// 不明状态
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
		// Session session = sf.openSession();
		Session session = sf.getCurrentSession();
		Transaction tx = session.beginTransaction();
		try {
			boolean isuserExist = false;
			// 查看用户是否存在
			Query q = session.createQuery("from User u where u.account = ?");
			q.setParameter(0, userName);
			User temp = null;
			List<User> users = q.list();
			for (User u : users) {
				temp = u;
				isuserExist = true;
			}

			if (isuserExist) {
				// 用户存在，密码是否匹配
				if (temp != null && temp.getPassword().equals(password)) {
					status = LoginBack.SUCCESS;

					lb.setRole(temp.getRole());
					lb.setRealName(temp.getRealName());

					// 返回好友、分组和群组信息和好友请求信息
					// Query qClass = session.createQuery("from Classify cs
					// where cs.owerName = ?");
					// qClass.setParameter(0, userName);
					// List<im.beans.Classify> classifys = qClass.list();
					//
					// ArrayList<LoginBack.Classify> classiyss = new
					// ArrayList<>();
					// ArrayList<LoginBack.User> backUsers = new ArrayList<>();
					// ArrayList<AddNewFriends> backANF = new ArrayList<>();
					// for(im.beans.Classify cs:classifys)
					// {
					// LoginBack.Classify tempcs = new LoginBack.Classify();
					// tempcs.setId(cs.getId());
					// tempcs.setClassifyName(cs.getClassifyName());
					//
					//
					// // 获取分组所有好友
					// Query qUserInClass = session.createQuery("from
					// Classify_User cu where cu.classify = ?");
					// qUserInClass.setParameter(0, cs);
					// List<Classify_User> cus = qUserInClass.list();
					// tempcs.setFriendCount(cus.size()+"");
					// classiyss.add(tempcs);
					// for(Classify_User tempCU:cus)
					// {
					// im.beans.User uTemp = tempCU.getUser();
					// LoginBack.User luTmep = new LoginBack.User();
					// luTmep.setAccount(uTemp.getAccount());
					// luTmep.setClassifyName(tempcs.getClassifyName());
					// luTmep.setId(uTemp.getId());
					// luTmep.setRealName(uTemp.getRealName());
					// luTmep.setClassifyID(cs.getId());
					// luTmep.setOnline(DefaultSessionManager.share().isSessionOnLine(uTemp.getAccount()));
					// backUsers.add(luTmep);
					// }
					//
					// }

					// 联合查询分组信息
					ArrayList<LoginBack.Classify> clas = new ArrayList<LoginBack.Classify>();
					Query qClass = session.createQuery("from Classify cs where cs.owerName = ?");
					qClass.setParameter(0, userName);
					List<im.beans.Classify> classifys = qClass.list();
					for (im.beans.Classify cs : classifys) {
						LoginBack.Classify tempcs = new LoginBack.Classify();
						tempcs.setId(cs.getId());
						tempcs.setClassifyName(cs.getClassifyName());
						clas.add(tempcs);
					}

					// 联合查询好友信息
					Query qUsers = session.createQuery(
							"select cls.id,cls.classifyName,u.id,u.account,u.realName from Classify cls,Classify_User cu,User u where cls.owerID = ? and cls.id = cu.classifyID and cu.userID = u.id");
					qUsers.setParameter(0, temp.getId());
					List results = qUsers.list();

					
					ArrayList<LoginBack.User> us = new ArrayList<LoginBack.User>();

					for (Object o : results) {
						Object[] colums = (Object[]) o;
						long classid = (long) colums[0];
						String classifyName = (String) colums[1];
						long userid = (long) colums[2];
						String account = (String) colums[3];
						String realName = (String) colums[4];

						LoginBack.User u = new LoginBack.User();
						u.setAccount(account);
						u.setRealName(realName);
						u.setClassifyID(classid);
						u.setClassifyName(classifyName);
						u.setId(userid);

						us.add(u);

					}

					// 获取好友请求
					Query qBackANF = session
							.createQuery("from AddNewFriends anf where anf.be_asked_id = ? and anf.state = ?");
					qBackANF.setParameter(0, (temp.getId()));
					qBackANF.setParameter(1, AddFriend.MsgBack.State.WAIT_TO_BE_DEALED);
					ArrayList<AddNewFriends> backANF = (ArrayList<AddNewFriends>) qBackANF.list();

					lb.setClassifys(clas);
					lb.setFriends(us);
					lb.setDnfs(backANF);

					// 一个设备，只能一个用户登录，检查设备是否有用户记录在设备表中在线,删除设备之前用户
					userID = temp.getId() + "";
				} else {
					status = LoginBack.PASSWORD_ERROR;
				}

			} else {
				status = LoginBack.USER_NOT_EXISTS;
			}

			session.getTransaction().commit();
		} catch (Exception e) {
			tx.rollback();
			// 服务器内部错误
			e.printStackTrace();
			status = LoginBack.FALSE;
		} finally {
			// session.close();
		}

		lb.setStatus(status);
		lb.setUserId(userID);

		// 去掉空格
		try {
			for (Classify csf : lb.getClassifys()) {
				BeanHelper.beanAttributeValueTrim(csf);
			}

			for (com.d404.server.Login2.LoginBack.User u : lb.getFriends()) {
				BeanHelper.beanAttributeValueTrim(u);
			}

			for (AddNewFriends a : lb.getDnfs()) {
				BeanHelper.beanAttributeValueTrim(a);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("login:" + JSON.toJSONString(lb));
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/json");
		response.getWriter().append(JSON.toJSONString(lb));

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	// 讲分组放入
	public void putClassify(LoginBack.Classify c, ArrayList<LoginBack.Classify> as) {
		for (LoginBack.Classify temp : as) {
			if (c.getId() == temp.getId()) {
				return;
			}
		}

		as.add(c);
	}

	/**
	 * 成功传输回去的类
	 * 
	 * @author 凯
	 *
	 */
	public static class LoginBack {
		public static final String USER_LOGED = "2";
		public static final String SUCCESS = "1";
		public static final String FALSE = "3";
		public static final String USER_NOT_EXISTS = "4";
		public static final String PASSWORD_ERROR = "5";

		// 状态码
		private String status;
		// 用户id
		private String userId;

		// 真实姓名
		private String realName;

		// 用户权限
		private String role;
		// 用户所有分组
		private List<Classify> classifys = new ArrayList<Classify>();
		// 用户所有好友
		private List<User> friends = new ArrayList<User>();
		// 所有好友请求
		private List<AddNewFriends> dnfs = new ArrayList<AddNewFriends>();

		public String getRealName() {
			return realName;
		}

		public void setRealName(String realName) {
			this.realName = realName;
		}

		public String getRole() {
			return role;
		}

		public void setRole(String role) {
			this.role = role;
		}

		public String getStatus() {
			return status;
		}

		public void setStatus(String status) {
			this.status = status;
		}

		public String getUserId() {
			return userId;
		}

		public void setUserId(String userId) {
			this.userId = userId;
		}

		public static class User {
			private long id;
			// 用户账号
			private String account;

			// 所在分组
			private String classifyName;

			// 所在分组ID
			private long classifyID;

			// 用户备注
			private String realName;

			// 是否在线
			private boolean online;

			public long getId() {
				return id;
			}

			public void setId(long id) {
				this.id = id;
			}

			public String getAccount() {
				return account;
			}

			public void setAccount(String account) {
				this.account = account;
			}

			public String getClassifyName() {
				return classifyName;
			}

			public void setClassifyName(String classifyName) {
				this.classifyName = classifyName;
			}

			public String getRealName() {
				return realName;
			}

			public void setRealName(String realName) {
				this.realName = realName;
			}

			public long getClassifyID() {
				return classifyID;
			}

			public void setClassifyID(long classifyID) {
				this.classifyID = classifyID;
			}

			public boolean getOnline() {
				return online;
			}

			public void setOnline(boolean online) {
				this.online = online;
			}

		}

		public static class Classify {
			private long id;
			private String classifyName;
			private String friendCount;

			public long getId() {
				return id;
			}

			public void setId(long id) {
				this.id = id;
			}

			public String getClassifyName() {
				return classifyName;
			}

			public void setClassifyName(String classifyName) {
				this.classifyName = classifyName;
			}

			public String getFriendCount() {
				return friendCount;
			}

			public void setFriendCount(String friendCount) {
				this.friendCount = friendCount;
			}

		}

		public List<Classify> getClassifys() {
			return classifys;
		}

		public void setClassifys(List<Classify> classifys) {
			this.classifys = classifys;
		}

		public List<User> getFriends() {
			return friends;
		}

		public void setFriends(List<User> users) {
			this.friends = users;
		}

		public List<AddNewFriends> getDnfs() {
			return dnfs;
		}

		public void setDnfs(List<AddNewFriends> dnfs) {
			this.dnfs = dnfs;
		}
	}

}
